/****************************************************
 * Description: ServiceImpl for ${model.label}
 * Copyright:   Copyright (c) ${model.year}
 * Company:     ${model.company}
 * @author      ${model.author}
 * @version     ${model.version}
 * @see
	HISTORY
    *  ${model.date} ${model.author} Create File
**************************************************/

package ${model.packageForServiceImpl};

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ${model.globalPackage}.framework.dao.XjjDAO;
import ${model.globalPackage}.framework.service.XjjServiceSupport;
import ${model.globalPackage}.sys.xfile.dao.XfileDao;
import ${model.globalPackage}.sys.xfile.entity.XfileEntity;
import ${model.globalPackage}.framework.exception.ValidationException;



import ${model.packageForModel}.${model.name?cap_first}Entity;
import ${model.packageForDAO}.${model.name?cap_first}Dao;
import ${model.packageForService}.${model.name?cap_first}Service;

import org.apache.commons.lang3.StringUtils;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ${model.name?cap_first}ServiceImpl extends XjjServiceSupport<${model.name?cap_first}Entity> implements ${model.name?cap_first}Service {

	@Autowired
	private ${model.name?cap_first}Dao ${model.name?uncap_first}Dao;

    @Autowired
    private XfileDao xfileDao;

	@Override
	public XjjDAO<${model.name?cap_first}Entity> getDao() {

		return ${model.name?uncap_first}Dao;
	}

    /**
    * 导入用户
    * @param fileId
    */
    public Map<String,Object> saveImport(Long fileId) throws ValidationException {
        //校验数据并返回合法数据
        List<${model.name?cap_first}Entity> ${model.name?uncap_first}EntityList = this.validImport(fileId);
        if(${model.name?uncap_first}EntityList==null||${model.name?uncap_first}EntityList.size()==0){
            throw new ValidationException("文件数据为空，请重新上传");
        }
        int trouble${model.name?cap_first}Cnt = 0;
        int okCnt = 0;
        //保存数据
        for (int i = 0; i < ${model.name?uncap_first}EntityList.size(); i++) {
            try {
                ${model.name?cap_first}Entity ${model.name?uncap_first}Entity = ${model.name?uncap_first}EntityList.get(i);
                ${model.name?uncap_first}Dao.save(${model.name?uncap_first}Entity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ValidationException(e.getMessage());
            }
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("allCnt", ${model.name?uncap_first}EntityList.size());
        map.put("trouble${model.name?cap_first}Cnt", trouble${model.name?cap_first}Cnt);
        map.put("okCnt", okCnt);
        return map;
    }

    private List<${model.name?cap_first}Entity> validImport(Long fileId) throws ValidationException{
        //获得上传文件
        XfileEntity xfile=xfileDao.getById(fileId);
        if(xfile==null){
            throw new ValidationException("未找到上传文件");
        }
        /**
        * 1.验证上传文件是否为空并且文件格式是否是xls
        */
        String fileName=xfile.getFileRealname();
        String prefix=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        if(!prefix.equals("xls") && !prefix.equals("xlsx")){
            throw new ValidationException("请上传xls或者xlsx格式的文件");
        }
        String[] content = null;
        Workbook workbook = null;
        Sheet sheet = null;
        int length = 0;
        try {
            File file = new File((xfile.getFilePath()));
            workbook = Workbook.getWorkbook(file);
            sheet = workbook.getSheet(0);
            length = sheet.getRows();
        } catch (Exception ex) {
            throw new ValidationException("文件格式转换异常");
        }
        /**
        * 2.验证上传文件中的Excel
        */

        StringBuilder validationMsg = new StringBuilder();;
        Cell cell = null;
        int columns = 1;
        if(sheet != null && sheet.getColumns() < columns){
                validationMsg.append("上传失败：上传文件中的Excel列数必须是"+columns+"列。<br/>");
        }
        List<${model.name?cap_first}Entity> ${model.name?uncap_first}EntityList=new ArrayList<${model.name?cap_first}Entity>();
        /**
        * 3.验证上传文件中的Excel每一行每一列都不为空
        */
        //TODO
        Long id = null;//id
        for (int i = 1; i < length; i++) {// 第2行开始
             content = new String[sheet.getColumns()];
             for (int j = 0; j < columns; j++) {
                  cell = sheet.getCell(j, i);
                  content[j] = cell.getContents().trim();
             }
             if(content[0] ==null || StringUtils.isBlank(content[0])) {
                  validationMsg.append("●文件中第" + (i+1) + "行不能为空。<br/>");
                  continue;
             }

             ${model.name?cap_first}Entity ${model.name?uncap_first}Entity = new ${model.name?cap_first}Entity();
             ${model.name?uncap_first}Entity.setId(id);
             ${model.name?uncap_first}EntityList.add(${model.name?uncap_first}Entity);
        }

        if(!StringUtils.isBlank(validationMsg.toString())) {
             throw new ValidationException(validationMsg.toString());
        }
        return ${model.name?uncap_first}EntityList;
    }


}
